import { jieMian } from '../JieMian.js'

class TanKuang extends HTMLDialogElement {
	biaoTi = null
	
	constructor() {
		super()

		// 关闭
		let guanBi = document.createElement('div')
		guanBi.style = `position: absolute; top: 0.5rem; right: 0.5rem; width: 1.2rem; height: 1.2rem; background: transparent; cursor: pointer;`
		guanBi.innerHTML = `<div style="width: 100%; height: 100%; background: #fff; clip-path: polygon(0% 0%, 50% 40%, 100% 0%, 60% 50%, 100% 100%, 50% 60%, 0% 100%, 40% 50%);"></div>`
		guanBi.addEventListener('pointerdown', () => this.close(), { capture: true }) // click pointerup 跟requestPointerLock有冲突
		this.appendChild(guanBi)
		// 标题
		this.biaoTi = document.createElement('div')
		this.biaoTi.style = `
			width: 100%;
			height: 2.2rem;
			font-size: 1.2rem;
			font-weight: 600;
			cursor: move;
			text-align: center;
			line-height: 2.2rem;
			background: linear-gradient(rgba(0, 0, 0, 0), rgba(0, 200, 255, 0.3)), linear-gradient(45deg, rgba(0, 0, 0, 0), rgba(0, 100, 200, 0.5));
		`
		this.biaoTi.addEventListener('pointerdown', () => {
			let pointermove = shiJian => {
				let { movementX, movementY } = shiJian
				let yangShi = getComputedStyle(this)
				let { top, left } = yangShi
				top = parseFloat(top)
				left = parseFloat(left)
				
				let shiTuKuang = this.getBoundingClientRect()
				let { x, y, width, height } = shiTuKuang // translate后left != x
				
				const clientWidth = document.documentElement.clientWidth
				const clientHeight = document.documentElement.clientHeight
				
				if (movementX + x > 0 && movementX + x < clientWidth - width) left += movementX
				if (movementY + y > 0 && movementY + y < clientHeight - height) top += movementY
				
				this.style.left = `${left}px`
				this.style.top = `${top}px`
			}
			let pointerup = () => {
				document.removeEventListener('pointermove', pointermove)
				document.removeEventListener('pointerup', pointerup)
			}
			document.addEventListener('pointermove', pointermove)
			document.addEventListener('pointerup', pointerup)
		})
		this.appendChild(this.biaoTi)
	}
	
	connectedCallback() {
		this.style = `
			${this.style.cssText}
			-webkit-mask: linear-gradient(rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 1) 1%, rgba(0, 0, 0, 1) 97%, rgba(0, 0, 0, 0) 100%);
			background: radial-gradient(rgba(100, 100, 255, 1), rgba(100, 100, 255, 0.5));
			backdrop-filter: blur(1rem);
			opacity: 0.9;
			border: 2px groove;
			border-image: linear-gradient(rgba(50, 100, 255, 1), rgba(50, 100, 255, 0.1), rgba(50, 100, 255, 1)) 10%;
			color: #fff;
			position: fixed;
			inset: 50%;
			transform: translate(-50%, -50%);
			margin: 0;
			z-index: 98;
			min-width: 10rem;
			min-height: 10rem;
		`
	}
	
	static get observedAttributes() {
		return ['biao-ti'];
	}
	
	attributeChangedCallback(name, oldValue, newValue) {
		if (name == 'biao-ti') this.biaoTi.innerText = newValue
	}
	
	jiaZai() {
		jieMian.shadowRoot.appendChild(this)
	}
}

customElements.define('tan-kuang', TanKuang, { extends: 'dialog' })